package top.laoshuzi.android.iotcamera.camera.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.subjects.PublishSubject
import top.laoshuzi.android.iotcamera.camera.bean.dto.CameraTargetDTO
import top.laoshuzi.android.iotcamera.camera.bean.dto.LightStateCmdDTO
import top.laoshuzi.android.iotcamera.camera.respository.CameraResposity
import top.laoshuzi.android.iotcamera.common.RxHelper
import top.laoshuzi.android.iotcamera.core.executors.AppSchedulers
import java.util.concurrent.TimeUnit

class CameraViewModel(private val cameraResposity: CameraResposity) : ViewModel() {

    private val disposables: CompositeDisposable = CompositeDisposable()

    private var cameraControlDirectionObserver = PublishSubject.create<CameraTargetDTO>()


    var lightStateObserver = MutableLiveData<LightStateCmdDTO>()
        private set

    var cameraDeviceId = ""
        private set

    init {
        cameraControlDirectionObserver.throttleFirst(200, TimeUnit.MILLISECONDS)
            .compose(RxHelper.observableToIo(AppSchedulers.MAIN_THREAD.scheduler))
            .subscribe { cameraTargetDTO ->
                cameraResposity.publishCameraControlDirection(cameraTargetDTO)
            }.run {
                disposables.add(this)
            }
    }

    override fun onCleared() {
        super.onCleared()
        disposables.clear()
        cameraResposity.unsubscribeLightState(cameraDeviceId)
    }

    fun publishCameraControlDirection(cameraTargetDTO: CameraTargetDTO) {
        cameraControlDirectionObserver.onNext(cameraTargetDTO)
    }

    fun publishLightState(id: String, lightStateCmdDTO: LightStateCmdDTO) {
        cameraResposity.publishLightState(id, lightStateCmdDTO)
    }

    fun subscribeLightState(id: String) {
        this.cameraDeviceId = id

        cameraResposity.subscribeLightState(id)
            .compose(RxHelper.observableToMain(AppSchedulers.NETWORK.scheduler))
            .subscribe {
                lightStateObserver.postValue(it)
            }.run {
                disposables.add(this)
            }
    }


}